#include "HttpServer.hpp"
#include "Protocol.hpp"
#include <memory>
#include "Util.hpp"

std::string Handle(std::string &message) // 返回一个http响应报文
{
    std::cout << message << std::endl;
    // 反序列化
    HttpRequest req = Deserialize(message);
    req.Print();

    // 返回响应
    std::string body;
    std::string response;
    if (Util::ReadFile(req._path, &body) == true)
    {
        response = "HTTP/1.0 200 OK" + SEP; // 响应状态行
        response += "Content-Length: " + std::to_string(body.size()) + SEP;
        // response += "Content-Type: text/html" + SEP;只接受html资源
        response += GetContentType(req._suffix); // 资源类型又后缀_suffix决定
        response += SEP;                         // 空行
        response += body;                        // 有效载荷
    }
    else//没找到资源则404错误
    {
        response = "HTTP/1.0 404 Not Found" + SEP;
        Util::ReadFile(wrongPage, &body);
        response += "Content-Length: " + std::to_string(body.size()) + SEP;
        response += GetContentType(".html");
        response += SEP;
        response += body;
    }

    //重定向测试
    // std::string response;
    // response = "HTTP/1.0 301 Moved Permanently" + SEP;
    // response += "Location: https://www.baidu.com/" + SEP;
    // response += SEP;

    //cookie与session测试
    // std::string response;
    // response = "HTTP/1.0 200 OK" + SEP;
    // response += "Set-Cookie: sessionid=1234abcd" + SEP;
    // response += SEP;
    return response;
}

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        exit(USAGE_ERR);
    }
    uint16_t port = atoi(argv[1]);
    std::unique_ptr<HttpServer> tsvr(new HttpServer(Handle, port));
    tsvr->InitServer();
    tsvr->Start();
    return 0;
}